package cn.iocoder.yudao.module.vote.service.voteHead;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.els.generatorCode.CodeGeneratorApi;
import cn.iocoder.yudao.module.vote.controller.admin.voteHead.vo.VoteHeadPageReqVO;
import cn.iocoder.yudao.module.vote.controller.admin.voteHead.vo.VoteHeadSaveReqVO;
import cn.iocoder.yudao.module.vote.controller.app.voteHead.vo.VoteResultRespVO;
import cn.iocoder.yudao.module.vote.dal.dataobject.voteHead.VoteHeadDO;
import cn.iocoder.yudao.module.vote.dal.mysql.voteHead.VoteHeadMapper;
import cn.iocoder.yudao.module.vote.dal.redis.VoteRedisDAO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.vote.enums.ErrorCodeConstants.HEAD_NOT_EXISTS;

/**
 * 投票头 Service 实现类
 *
 * @author 吕小文
 */
@Service
@Validated
public class VoteHeadServiceImpl implements VoteHeadService {

    @Resource
    private VoteHeadMapper headMapper;

    @Resource
    private  VoteRedisDAO voteRedisDAO;
    
    @Resource
    private CodeGeneratorApi codeGeneratorApi;

    @Override
    public Long createHead(VoteHeadSaveReqVO createReqVO) {
        // 插入
        VoteHeadDO head = BeanUtils.toBean(createReqVO, VoteHeadDO.class);
        //获取投票编码
        String actVoteNumber = codeGeneratorApi.getNextCode("actVoteNumber");
        head.setActNo(actVoteNumber);
        headMapper.insert(head);
        // 返回
        return head.getId();
    }

    @Override
    public void updateHead(VoteHeadSaveReqVO updateReqVO) {
        // 校验存在
        validateHeadExists(updateReqVO.getId());
        // 更新
        VoteHeadDO updateObj = BeanUtils.toBean(updateReqVO, VoteHeadDO.class);
        headMapper.updateById(updateObj);
    }

    @Override
    public void deleteHead(Long id) {
        // 校验存在
        validateHeadExists(id);
        // 删除
        headMapper.deleteById(id);
    }

    private void validateHeadExists(Long id) {
        if (headMapper.selectById(id) == null) {
            throw exception(HEAD_NOT_EXISTS);
        }
    }

    @Override
    public VoteHeadDO getHead(Long id) {
        return headMapper.selectById(id);
    }

    @Override
    public PageResult<VoteHeadDO> getHeadPage(VoteHeadPageReqVO pageReqVO) {
        return headMapper.selectPage(pageReqVO);
    }

    /**
     * 投票
     * @param createReqVO
     */
    @Override
    public void vote(VoteHeadSaveReqVO createReqVO) {
        voteRedisDAO.setAppSecret("VOTEP0001","2","2");
    }

    @Override
    public VoteResultRespVO queryVote(Long id) {
        VoteResultRespVO vo = new VoteResultRespVO();
        voteRedisDAO.getAppSecret("VOTEP0001","1");
        return null;
    }

}